package com.minelx.woods.server.perspective;

import com.minelx.woods.server.common.JWToken;
import com.minelx.woods.server.common.Parameters;
import com.minelx.woods.server.entity.Users;
import io.jsonwebtoken.Claims;
import org.springframework.http.ResponseEntity;

public class AuthenticatedProcessor {

	private final IProcedure procedure;

	private final Users users;

	private final String token;

	public AuthenticatedProcessor(IProcedure procedure, Users users, String token) {
		this.procedure = procedure;
		this.users = users;
		this.token = token;
	}

	public Object proceed() {
		if (!procedure.annotatedBy(Authenticated.class)) { // not authenticated interface
			return procedure.proceed();
		}
		// do authentication
		String user = JWToken.parse(token).getSubject();
		if (users.id(user).values() != null) { // token passed
			procedure.parameters().annotatedBy(UserName.class).set(user);
			return procedure.proceed();
		}
		// failed authentication
		return ResponseEntity.badRequest().build();
	}
}
